﻿$(document).ready(function() {

	$.namespace("mth", {
		inherited: true,

		InitialiseControl: function() {
			$.fn.mth.LoadMthGrid();
		},

		LoadMthGrid: function() {

			var tabContent = $("#MonthsContainer").children(".TabContent");
			var mthid = 0;

			/*** start mth-category grid set up ***/
			var mcProxy = new Ext.data.HttpProxy({
				url: 'Data/MthCategories.aspx'
			});

			var mcReader = new Ext.data.JsonReader({
				root: 'Data',
				totalProperty: 'Count',
				idProperty: 'CategoryId',
				fields: [
					{ name: 'MthCategoryId', type: 'int' },
					{ name: 'MthId', type: 'int' },
					{ name: 'CategoryId', type: 'int' },
					{ name: 'CategoryName', type: 'string' },
					{ name: 'BaseBudgetAmount', type: 'float', allowBlank: false },
					{ name: 'BudgetAmount', type: 'float', allowBlank: false },
					{ name: 'CarriedOverBudget', type: 'float', allowBlank: false },
					{ name: 'InitiallySet', type: 'boolean' },
					{ name: 'FinallySet', type: 'boolean' },
					{ name: 'HasSpendings', type: 'boolean' }
				]
			});

			var mcWriter = new Ext.data.JsonWriter({
				encode: true,   // <-- don't return encoded JSON -- causes Ext.Ajax#request to send data using jsonData config rather than HTTP params
				writeAllFields: true
			});

			var mcStore = new Ext.data.Store({
				id: 'dsMthCategories',
				proxy: mcProxy,
				reader: mcReader,
				baseParams: { xaction: "LISTING" },
				//writer: mcWriter,    // <-- plug a DataWriter into the store just as you would a Reader
				listeners: {
					'beforeload': function(store, options) {
						options.params['mthId'] = mthid;
					},
					'load': function(store, records, options) {
						var mcRefresh = Ext.getCmp('mcRefresh');
						var mcSelectAll = Ext.getCmp('mcSelectAll');
						var mcUpdate = Ext.getCmp('mcUpdate');
						var mcCarryOver = Ext.getCmp('mcCarryOver');

						// by default disable the button
						mcRefresh.disable();
						mcSelectAll.disable();
						mcUpdate.disable();
						mcCarryOver.disable();

						// now determine if they should be enabled
						if (records.length > 0) {
							var spendingsExist;
							$.each(records, function(index, record) {
								if (record.data.HasSpendings) {
									spendingsExist = true;
								}
							});

							if (!spendingsExist) {
								mcUpdate.enable();
								mcSelectAll.enable();
								mcCarryOver.enable();
							}
							mcRefresh.enable();
						}
					}
				}
			});

			var checkColumn = new Ext.grid.CheckColumn({
				header: 'Included',
				dataIndex: 'FinallySet',
				align: 'center'
			});

			var mcColModel = new Ext.grid.ColumnModel({
				defaults: {
					sortable: true
				},
				columns: [
					checkColumn,
					{ header: 'Category Name', dataIndex: 'CategoryName' },
					{ header: 'Budget', dataIndex: 'BaseBudgetAmount', align: 'right', xtype: 'numbercolumn', format: '$0,0.00' },
					{ header: 'Carry Over', dataIndex: 'CarriedOverBudget', align: 'right', xtype: 'numbercolumn', format: '$0,0.00' },
					{ header: 'Actual Budget', dataIndex: 'BudgetAmount', align: 'right', xtype: 'numbercolumn', format: '$0,0.00', editor: new Ext.form.NumberField({}) }
				]
			});

			var mcUpdateBtn = new Ext.Button({
				id: 'mcUpdate',
				text: 'Update',
				iconCls: 'silk-accept',
				disabled: true,
				handler: function(btn, ev) {
					var data = [];
					$.each(mcGrid.getStore().getModifiedRecords(), function(index, record) {
						if (true) { }
						data.push(record.data);
					});

					if (data.length > 0) {
						$.ajax({
							type: "POST",
							url: 'Data/MthCategories.aspx?xaction=batchupdate',
							data: JSON.stringify(data),
							contentType: "application/json;",
							dataType: "json",
							success: function(msg) {
								mcGrid.getStore().commitChanges();
								mcGrid.getStore().reload();
								var currMonth = $.fn.global.CurrentMonth();
								if (currMonth != null) {
									if (data[0].MthId == currMonth.MthId) {
										$.fn.global.CurrentMonthCategories(msg.Data);
									}
								}
							},
							error: function(msg) {
								alert('An error occured during the update.');
							}
						});
					}
				}
			});

			var mcSelectAllBtn = new Ext.Button({
				id: 'mcSelectAll',
				text: 'Select All',
				iconCls: 'silk-user-add',
				disabled: true,
				handler: function(btn, e) {
					var mcGrid = Ext.getCmp('mcGrid');

					$(".x-grid3-check-col").each(function(i, container) {
						var index = mcGrid.getView().findRowIndex(container);
						var record = mcGrid.store.getAt(index);
						record.set('FinallySet', true);
					});
				}
			});

			var mcCarryOverBtn = new Ext.Button({
				id: 'mcCarryOver',
				text: 'Carry Over',
				iconCls: 'silk-application-go',
				disabled: true,
				handler: function(btn, e) {
					var mcGrid = Ext.getCmp('mcGrid');
					var records = mcGrid.getStore().data.items;

					$.each(records, function(index, record) {
						var combinedValue = record.data.BaseBudgetAmount + record.data.CarriedOverBudget;
						record.set('BudgetAmount', combinedValue);
					});
				}
			});

			var mcRefreshBtn = new Ext.Button({
				id: 'mcRefresh',
				text: 'Refresh',
				iconCls: 'silk-table-refresh',
				disabled: true,
				handler: function() {
					mcGrid.getStore().rejectChanges();
					mcGrid.getStore().reload();
				}
			});

			var editor = new Ext.ux.grid.RowEditor({
				saveText: 'Update'
			});

			var mcGrid = new Ext.grid.GridPanel({
				//renderTo: 'DataGrid',
				id: 'mcGrid',
				iconCls: 'icon-grid',
				frame: true,
				title: 'Month Categories',
				loadMask: true,
				autoScroll: true,
				height: 300,
				store: mcStore,
				plugins: [checkColumn, editor],
				colModel: mcColModel,
				tbar: [mcUpdateBtn, '-', mcSelectAllBtn, '-', mcCarryOverBtn, '-', '->', '-', mcRefreshBtn],
				viewConfig: {
					forceFit: true
				}
			});

			/*** end mth-category grid set up ***/

			/*** start mth grid set up ***/

			var mthStore = new Ext.data.JsonStore({
				fields: ['MonthIndex', 'MonthName'],
				data: $.fn.global.Months(true)
			});

			var proxy = new Ext.data.HttpProxy({
				url: 'Data/Months.aspx',
				listeners: {
					'write': function(proxy, action, data, response, records, options) {
						if (action == 'create') {
							records.store.loadData(response);
						}
					}
				}
			});

			var reader = new Ext.data.JsonReader({
				root: 'Data',
				totalProperty: 'Count',
				idProperty: 'MthId',
				fields: [
					{ name: 'MthId', type: 'int' },
					{ name: 'Month', type: 'int', allowBlank: false },
					{ name: 'Year', type: 'int', allowBlank: false },
					{ name: 'TotalIncome', type: 'float', allowBlank: false },
					{ name: 'Timestamp', type: 'date', dateFormat: 'M$' },
					{ name: 'Version', type: 'auto' }
				]
			});

			var writer = new Ext.data.JsonWriter({
				encode: true,   // <-- don't return encoded JSON -- causes Ext.Ajax#request to send data using jsonData config rather than HTTP params
				writeAllFields: true
			});

			var newMth;
			var store = new Ext.data.Store({
				id: 'dsMths',
				restful: false,     // <-- This Store is RESTful
				proxy: proxy,
				reader: reader,
				writer: writer,    // <-- plug a DataWriter into the store just as you would a Reader
				listeners: {
					'update': function(store, record, operation) {
						store.commitChanges();
						store.reload();
					},
					'beforesave': function(store, data) {
						newMth = data.create[0].data;
					},
					'save': function(store, batchNumber, data) {
						var dt = new Date();
						if (newMth.Month == dt.getMonth() + 1 && newMth.Year == dt.getYear()) {
							$.fn.global.GetCurrentMonth()
						}
					}
				}
			});

			var colModel = new Ext.grid.ColumnModel({
				defaults: {
					sortable: true
				},
				columns: [
				//{ header: 'MthId', dataIndex: 'MthId' },
					{header: 'Month', dataIndex: 'Month', align: 'center', renderer: $.fn.global.MonthRenderer,
					editor: new Ext.form.ComboBox({
						store: mthStore,
						displayField: 'MonthName',
						valueField: 'MonthIndex',
						//				hiddenName: 'SelectedMonth',
						typeAhead: true,
						mode: 'local',
						triggerAction: 'all',
						emptyText: 'Select a month...'
					})
				},
					{ header: 'Year', dataIndex: 'Year', align: 'center', xtype: 'numbercolumn', format: '0', editor: new Ext.form.NumberField({}) },
					{ header: 'Total Income', dataIndex: 'TotalIncome', align: 'right', xtype: 'numbercolumn', format: '$0,0.00', editor: new Ext.form.NumberField({}) }
				]
			});

			// use RowEditor for editing
			var editor = new Ext.ux.grid.RowEditor({
				saveText: 'Update'
			});

			var grid = new Ext.grid.GridPanel({
				//renderTo: 'DataGrid',
				iconCls: 'icon-grid',
				frame: true,
				title: 'Months',
				loadMask: true,
				autoScroll: true,
				height: 300,
				store: store,
				plugins: [editor],
				colModel: colModel,
				tbar: [{
					text: 'Add',
					iconCls: 'silk-add',
					handler: function(btn, ev) {
						var u = new grid.store.recordType({
							Description: '',
							Amount: '',
							IsActive: true
						});
						editor.stopEditing();
						grid.store.insert(0, u);
						editor.startEditing(0);
					}
				}, '-', '->', '-', {
					text: 'Refresh',
					iconCls: 'silk-table-refresh',
					handler: function() {
						grid.getStore().rejectChanges();
						grid.getStore().reload();
					}
				}
				],
				viewConfig: {
					forceFit: true
				},
				listeners: {
					'rowclick': function(grid, rowIndex, e) {
						if (true) { }
						mthid = grid.store.data.items[rowIndex].data.MthId;
						mcGrid.store.load();
					}
				}

			});

			/*** end mth grid set up ***/

			/*** start panel set up ***/
			var mthPanel = new Ext.Panel({
				id: 'mthPanel',
				//title: 'Panel Title',
				layout: 'column',
				padding: 0,
				bodyBorder: false,
				border: false,
				items: [{
					id: 'regMths',
					border: false,
					padding: '0px 5px 0px 0px',
					columnWidth: 0.60,
					//verticalAlign: 'top',
					items: [grid]
					//html: '<p>This is some short content.</p>'*/
				}, {
					id: 'regMthCategory',
					border: false,
					padding: '0px 0px 0px 5px',
					columnWidth: 0.40,
					//verticalAlign: 'top',
					items: [mcGrid]
					//html: '<p>This is some longer content.</p><p>This is some longer content.</p><p>This is some longer content.</p><p>This is some longer content.</p><p>This is some longer content.</p><p>This is some longer content.</p>'
}]
				});

				//tab.items.add(mthPanel);
				mthPanel.render(tabContent[0]);
				/*** end panel set up ***/

				store.load();
				mcStore.load();
			}
		});
	});